package com.ken.common.utils;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Base64;

public class imgUtil {
    public static File Base64ToFileUtil(String base64Image,String ImgEncoder) throws Exception{
        // 解码Base64字符串为字节数组
        byte[] imageBytes = Base64.getDecoder().decode(base64Image);

        // 创建一个临时文件
        Path tempFile = Files.createTempFile("ken-", "."+ImgEncoder); // "prefix-" 是前缀，".suffix" 是后缀，可以自定义
        Files.write(tempFile, imageBytes);

        // 如果需要File对象，可以从Path转换而来
        File file = tempFile.toFile();
        //储存完后删除临时文件
        tempFile.toFile().deleteOnExit();
        return file;
    }
    public static String downLoadImgToBase64(String imageUrl) throws IOException {
        URL url = new URL(imageUrl);
        BufferedImage image = ImageIO.read(url);
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        ImageIO.write(image, "jpg", byteArrayOutputStream);
        byte[] imageBytes = byteArrayOutputStream.toByteArray();
        return Base64.getEncoder().encodeToString(imageBytes);
    }
}
